//
//  NetworkTool.swift
//  jxc_ios
//
//  Created by dongzhenyu on 2018/5/11.
//  Copyright © 2018年 dongzhenyu. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import RxCocoa
import RxSwift


enum MethodType {
    case get
    case post
}

enum CBNetError : Swift.Error {
    case NetFailded
    case HTTPFailed
    case MapperError
    case CustomError(msg:String,code:Int)
    
    func show() -> CBNetError{
        switch self {
        case .NetFailded:break
        case .HTTPFailed:break
        case .MapperError:break
        case .CustomError(let _, let _):break
        }
        return self
    }
}


class NetworkTool {
    
    //响应式网络请求
    class func requestData(url: String, param: [String: Any]?, type: MethodType = MethodType.post, isShowCustomErr:Bool = true) -> Observable<JSON> {
        return Observable<JSON>.create({ (observer) -> Disposable in
            //如果网络错误，返回报错
            if !NetworkTool.isNetConnect() {
                observer.onError(CBNetError.NetFailded.show())
            }
            let method = (type == .get) ? HTTPMethod.get : HTTPMethod.post
            let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 15
            manager.request(url, method: method, parameters: param).responseJSON { (response) in
                switch response.result {
                case .success(_):
                    if let dictJson = response.result.value as? [String : Any] {
                        let json = JSON(dictJson)
print("url:\n\(url)")
print("param:\n\(param?.description ?? "")")
print("json:\n\(json.description)")
                        if json["code"].intValue == 1 {
                            observer.onNext(json)
                            observer.onCompleted()
                        } else {
                            if isShowCustomErr {
                                MainTools.makeToast(message: json["message"].stringValue)
                            }
                            observer.onError(CBNetError.CustomError(msg: json["message"].stringValue, code: json["code"].intValue))
                        }
                    } else {
                        MainTools.makeToast(message: "接口格式错误,请联系管理员")
                        observer.onError(CBNetError.MapperError.show())
                    }
                case .failure(_):
                    MainTools.makeToast(message: "服务器错误,请联系管理员")
                    observer.onError(CBNetError.HTTPFailed.show())
                }
            }
            return Disposables.create {}
        })
    }
    
    //检测网络是否正常
    class func isNetConnect() -> Bool {
        let reachability:Reachability = Reachability()!
        if !reachability.isReachableViaWiFi && !reachability.isReachableViaWWAN {
            MainTools.makeToast(message: "网络错误,请检查网络设置")
            return false
        } else {
            return true
        }
    }
}
